// pages/safetysence/safetysence.js
var util = require('../../utils/util.js')
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    list: [],
    nodata: 'none',
    accounts: ["请选择"],
    accountIndex: 0,
    modalComfirm: false,
    scrollTop: 0,
    hide: "block",
    loading: 1,
    loadDealing: 0, //判断是否 由 待处理变成处理中
    catchMove: true,
    /**
     * 页面配置
     */
    winWidth: 0,
    winHeight: 0,
    // tab切换
    identityId: null,
    tabTitle: "待处理",
    pageTimes: 1,
    noMore: 0,
    isSupervsor: false,
    isSupervising: false,
    isSuddenSupervising: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.departmentType == "教育局" || app.globalData.departmentType == "区教育局") {
      this.setData({
        isSupervsor: true,
        isSupervising: app.globalData.isSupervising,
        isSuddenSupervising: app.globalData.isSuddenSupervising
      })
    }
    let identityTrue = false
    if (app.globalData.features == "35" || app.globalData.identityId == -1 || app.globalData.identityId == -2) {
      identityTrue = true
    }
    this.setData({
      identityId: app.globalData.identityId,
      showForward: identityTrue ? 0 : 1
    })
    if (identityTrue) {
      this.setData({
        tabTitle: "我的上报"
      })
    }

    wx.getSystemInfo({
      success: res => {
        this.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });

    // 初始化 取待处理 隐患
    this.getSafetySenceList(6)
    wx.request({
      url: app.inspectUrl + '/WeChat/weChatSystem/getAllValidInspectItems',
      method: 'POST',
      data: {
        schoolId: app.globalData.departmentId
      },
      dataType: 'json',
      success: res => {
        // let accounts = ["请选择"],
        //   categoryId = [0]
        let accounts = [],
          categoryId = []
        for (let i = 0; i < res.data.length; i++) {
          accounts.push({
            item: res.data[i].category,
            checked: false
          })
          categoryId.push(res.data[i].categoryId)
        }
        this.setData({
          accounts: accounts,
          categoryId: categoryId
        })
      }
    })
  },
  onShow: function () {
    if (this.data.loadDealing == 1) {
      this.setData({
        currentTab: 1,
        loadDealing: 0,
        loading: 0
      })
      this.getSafetySenceList(7)
    }
    if(app.globalData.departmentType == "教育局" || app.globalData.departmentType == "区教育局"){
      this.setData({
        isSupervising: app.globalData.isSupervising,
        isSuddenSupervising: app.globalData.isSuddenSupervising
      })
    }

  },


  getSafetySenceList: function (status) {
    this.setData({
      wait: 1
    })
    let interfaceUrl
    let identityTrue = false
    if (app.globalData.features == "35" || app.globalData.identityId == -1 || app.globalData.identityId == -2) {
      identityTrue = true
    }
    if (identityTrue) {
      interfaceUrl = app.inspectUrl + '/WeChat/weChatSystem/listMyReportSafetyScene'
    } else {
      if (app.globalData.departmentType == "教育局" || app.globalData.departmentType == "区教育局") {
        interfaceUrl = app.inspectUrl + '/WeChat/weChatSystem/getSafetySceneListForEdu'
      } else {
        interfaceUrl = app.inspectUrl + '/WeChat/weChatSystem/getSafetySceneList'
      }

    }


    wx.request({
      url: interfaceUrl,
      method: 'POST',
      data: {
        userId: app.globalData.userId,
        schoolId: app.globalData.departmentId,
        identityId: app.globalData.identityId,
        status: status,
        pageTimes: this.data.pageTimes
      },
      dataType: 'json',
      success: res => {

        console.log(" app.globalData.userId================", app.globalData.userId)
        console.log("res.data===========================", res.data)
        if (res.data.data.length == 0) {
          this.setData({
            loading: 0,
            nodata: 'flex'
          })
          return
        } else {
          this.setData({
            loading: 0,
            nodata: 'none'
          })
        }
        let list = []
        for (let i = 0; i < res.data.data.length; i++) {
          let photo = ""
          if (res.data.data[i].photo == "" || !res.data.data[i].photo) {
            photo = "/images/nophoto.png"
          } else {
            photo = app.imageUrl + res.data.data[i].photo.split(',')[0]
          }

          list.push({
            id: res.data.data[i].id,
            address: res.data.data[i].address,
            safetyLevel: res.data.data[i].safetyLevel,
            category: res.data.data[i].categoryName,
            photo: photo,
            reporter: res.data.data[i].reportName,
            time: res.data.data[i].createTime,
            status: res.data.data[i].status,
            content: res.data.data[i].content,
            modifyTime: res.data.data[i].modifyTime,
            //评价
            evaluate: res.data.data[i].reporter == app.globalData.userId ? 1 : 0
            // userPush:res.data.data[i].userPush    已推送 负责人
          })

        }

        // console.log(list)
        let listRes
        // (this.data.list.concat(list)))
        if (this.data.change == 1) {
          listRes = list
        } else {
          let ids = this.data.list.map(item => item.id)
          listRes = this.data.list
          for (let i = 0; i < list.length; i++) {
            ids.indexOf(list[i].id) == -1 ? listRes.push(list[i]) : ''
          }
        }
        console.log(listRes)
        // if (status + this.data.currentTab == 6) {
        this.setData({
          list: listRes
        })
        if ("NO" == res.data.isEnd) {
          this.setData({
            noMore: 0,
            pageTimes: this.data.pageTimes + 1
          })
        } else {
          this.setData({
            noMore: 1
          })
        }
        // }


        // console.log(this.data.list)
      },
      fail: res => {
        wx.showToast({
          title: '网络异常！',
          image: '/images/warning.png'
        })
        this.setData({
          catchMove: true
        })
      },
      complete: () => {
        this.setData({
          wait: 0,
          catchMove: true
        })
        setTimeout(() => {
          this.setData({
            change: 0
          })
        }, 300)

      }



    })
  },

  scrolltolower: function () {
    // console.log(12)
    if (this.data.noMore == 0 && this.data.wait == 0) {
      this.setData({
        catchMove: false
      })
      if (this.data.currentTab == 0) {
        this.getSafetySenceList(6)
      } else if (this.data.currentTab == 1) {
        // console.log('处理中')
        this.getSafetySenceList(7)
      } else {
        this.getSafetySenceList(5)
      }
    }
  },

  report: util.throttle(function (e) {
    if (this.data.isSupervising) {
      wx.navigateTo({
        url: `/pages/safetysenceReport/safetysenceReport?type=0&isSupervising=${this.data.isSupervising}`,
      })
    } else {
      wx.navigateTo({
        url: '/pages/safetysenceReport/safetysenceReport?type=0'
      })
    }

  }),

  dealnow: util.throttle(function (e) {
    // 需要传参id 根据id向后台请求safetysenceDeal应显示的数据
    wx.navigateTo({
      url: '/pages/safetysenceDeal/safetysenceDeal?id=' + e.currentTarget.id,
    })
  }),

  forward: function (e) {
    this.setData({
      modalName: null
    })
    let target = this.data.selectedCategory.index
    let content = '转发到' + this.data.selectedCategory.item
    // if (target != 0) {
    //   wx.showModal({
    //     content: '确定将此事件' + content + "?",
    //     success: res => {
    //       if (res.confirm) {
    wx.showLoading({
      title: '正在处理',
      mask: true
    })
    wx.request({
      url: app.inspectUrl + '/WeChat/weChatSystem/forwardSafetyScene',
      method: 'POST',
      data: {
        id: this.data.forwardId,
        content: content,
        reporter: app.globalData.userId,
        categoryId: this.data.categoryId[target]
      },
      dataType: 'json',
      success: res => {

        if (res.data.res == "success") {
          wx.showToast({
            title: '转发成功',
            mask: true,
            duration: 800
          })
          this.setData({
            list: [],
            pageTimes: 1,
            loading: 1,
            noMore: 0
          })
          this.getSafetySenceList(6)
          let safetySceneId = res.data.msg
          // 推送

          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/getAccessTokenForSendMsg',
            method: 'GET',
            dataType: 'json',
            success: res => {
              console.log(res)
              let access_token = res.data.access_token
              wx.request({
                url: app.inspectUrl + '/WeChat/weChatSystem/getChargeManWeChatId',
                method: 'POST',
                data: {
                  categoryId: this.data.categoryId[target],
                  schoolId: app.globalData.departmentId
                },
                dataType: 'json',
                success: res => {
                  let unbind = []
                  for (let i = 0; i < res.data.length; i++) {
                    if (res.data[i].res == "success") {
                      let datetime = util.formatTime(new Date())
                      wx.request({
                        url: app.inspectUrl + '/WeChat/weChatSystem/sendMessage',
                        data: {
                          template: 1,
                          accessToken: access_token,
                          touser: res.data[i].msg,
                          safetySceneId: safetySceneId,
                          data: {
                            first: {
                              value: "【安全现场隐患】"
                            },
                            keyword1: {
                              value: app.globalData.realname
                            },
                            keyword2: {
                              value: datetime
                            },
                            keyword3: {
                              value: `转发一条安全隐患到${this.data.selectedCategory.item}类型，请及时处理！`
                            }
                          }
                        },
                        method: 'POST',
                        dataType: 'json'
                      })
                    } else {
                      unbind.push(res.data[i].msg)

                    }
                  }
                  if (unbind.length != 0) {

                    let msg = unbind.join("、") + "主管未绑定服务号，无法正常接收推送！"
                    wx.showModal({
                      title: "提示",
                      showCancel: false,
                      content: msg,
                    })
                  }
                }
              })
            }
          })

        } else {
          wx.showToast({
            title: res.data.msg,
            image: "/images/error.png"
          })
        }
      },
      fail: res => {
        wx.showToast({
          title: '网络异常！',
          image: '/images/warning.png'
        })
      }
    })
    //       }
    //     }
    //   })
    // }
  },

  showHistory: util.throttle(function (e) {
    console.log("e====================", e)
    wx.navigateTo({
      url: '/pages/safetysenceHistory/safetysenceHistory?id=' + e.currentTarget.id + `&evaluate=` + e.currentTarget.dataset.evaluate
    })
  }),

  handletouchstart: function (e) {
    console.log(e)
    this.setData({
      touchStart: e.changedTouches[0].clientY,
      touchStartSymbol: 1
    })
  },

  handletouchmove: function (e) {
    console.log(e)
    // console.log(e.changedTouches[0].clientY)
    // if(this.noMore==0) return
    if (this.data.touchStartSymbol == 1) {
      if (this.data.touchStart > e.changedTouches[0].clientY) {
        this.setData({
          hide: 'none',
          touchStartSymbol: 0,
          touchNow: e.changedTouches[0].clientY
        })
      } else {
        this.setData({
          hide: 'block',
          touchStartSymbol: 0,
          touchNow: e.changedTouches[0].clientY
        })
      }
    } else {
      if (this.data.touchNow > e.changedTouches[0].clientY) {
        this.setData({
          hide: 'none',
          touchStartSymbol: 0,
          touchNow: e.changedTouches[0].clientY
        })
      } else {
        this.setData({
          hide: 'block',
          touchStartSymbol: 0,
          touchNow: e.changedTouches[0].clientY
        })
      }
    }
  },

  /**
   * 滑动切换tab
   */
  bindChange: util.throttle(function (e) {
    console.log(e)
    this.setData({
      list: [],
      pageTimes: 1,
      loading: 1,
      noMore: 0,
      change: 1,
      catchMove: false,
      hide: "block",
      currentTab: e.detail.current
    })

    if (this.data.currentTab == 0) {
      this.getSafetySenceList(6)
    } else if (this.data.currentTab == 1) {
      // console.log('处理中')
      this.getSafetySenceList(7)
    } else {
      this.getSafetySenceList(5)
    }
    this.setData({
      currentTab: e.detail.current
    })
  }, 150),

  /**
   * 点击tab切换
   */
  swichNav: function (e) {
    this.setData({
      list: [],
      pageTimes: 1,
      loading: 1,
      noMore: 0,
      change: 1,
      catchMove: false,
      hide: "block",
      currentTab: e.currentTarget.dataset.current
    })
    if (this.data.currentTab == 0) {
      this.getSafetySenceList(6)
    } else if (this.data.currentTab == 1) {
      // console.log('处理中')
      this.getSafetySenceList(7)
    } else {}
  },

  showModal(e) {
    console.log(e)
    let accounts = this.data.accounts.map((item, index) => {
      return {
        item: item.item,
        checked: false
      }
    })
    this.setData({
      modalName: "RadioModal",
      accounts: accounts,
      selectedCategory: {},
      modalComfirm: false,
      forwardId: e.currentTarget.dataset.id
    })
  },

  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  radioSelect(e) {
    console.log(e)
    let radioIndex = e.currentTarget.dataset.index,
      accounts = this.data.accounts.map((item, index) => {
        return {
          item: item.item,
          checked: index == radioIndex ? true : false
        }
      }),
      status
    this.setData({
      accounts: accounts,
      selectedCategory: {
        "index": radioIndex,
        "item": e.currentTarget.dataset.item
      }
    })
    if (this.data.selectedCategory) status = true
    else status = false
    this.setData({
      modalComfirm: status
    })
  },

})